package com.wushi.lenovo.asia5b.app_di.login.presenter;

import com.mvp.base.model.ResultModel;
import com.mvp.helper.WCallBack;
import com.mvp.networking.CustomThrowable;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.login.mvpview.LoginUserActivityView;
import com.wushi.lenovo.asia5b.app_di.other.presenter.CodePresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.other.CacheType;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;
import com.wushi.lenovo.asia5b.app_model.result.LoginResModel;
import com.wushi.lenovo.asia5b.app_push.PushHelper;
import com.wushi.lenovo.asia5b.app_utils.SystemUtil;
import com.wushi.lenovo.asia5b.app_utils.helper.CacheHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by zhangyuncai on 2018/11/29.
 */
public class LoginUserActivityPresenter extends CodePresenter<LoginUserActivityView> {

    @Inject
    public LoginUserActivityPresenter(ApiService apiService) {
        super(apiService);
    }

    //获取国家列表
    public void getCountrys() {
        CacheHelper.getCountrys(new WCallBack<List<CountryModel>>() {
            @Override
            public void callback(List<CountryModel> countryModels) {
                getView().getCountrysResult(countryModels);
            }
        }, CacheType.LOCAL);
    }


    /**
     * 普通登录
     *
     * @param email
     * @param password
     */
    public void login(String email, String password) {

        Map<String, Object> map = MapHelper.newHashMap();
        map.put("login_credential", "" + email);
        map.put("password", "" + password);
        map.put("app_register_id", "" + PushHelper.getRegistrationId());
        map.put("app_os", 1);//1 = Android , 2 = IOS
        SystemUtil.addSystemParam(map);
        baseSubscribe(getUserInfoObservable(apiService.login(map))
                , userInfoResultModel -> {
                    loginResult(userInfoResultModel, false);
                });
    }

    /**
     * 短信登录
     *
     * @param country_id
     * @param login_credential
     * @param otp
     */
    public void loginSms(String country_id, String login_credential, String otp) {
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("country_id", "" + country_id);
        map.put("login_credential", "" + login_credential);
        map.put("otp", "" + otp);
        map.put("app_os", 1);//1 = Android , 2 = IOS
        map.put("app_register_id", "" + PushHelper.getRegistrationId());
        SystemUtil.addSystemParam(map);
        baseSubscribe(getUserInfoObservable(apiService.loginSms(map))
                , userInfoResultModel -> {
                    loginResult(userInfoResultModel, true);
                });
    }

    public void loginResult(ResultModel<UserInfo> userInfoResultModel, boolean isEmail) {
        if (userInfoResultModel.isSuccess() && userInfoResultModel.getData() != null) {
            UserRepository.setUserInfo(userInfoResultModel.getData());
            EventBus.getDefault().post(new LoginEvent(CommonConstant.LOGIN_SUCCESS));
            ToastUtil.showToast(userInfoResultModel.getMsg());
        }
        getView().loginResult(userInfoResultModel.isSuccess(), isEmail);
    }

    public Observable<ResultModel<UserInfo>> getUserInfoObservable(Observable<ResultModel<LoginResModel>> observable) {
        return observable.flatMap(new Function<ResultModel<LoginResModel>, ObservableSource<ResultModel<UserInfo>>>() {
            @Override
            public ObservableSource<ResultModel<UserInfo>> apply(ResultModel<LoginResModel> loginResModelResultModel) throws Exception {
                if (loginResModelResultModel.isSuccess()) {
                    final LoginResModel loginResModel = loginResModelResultModel.getData();
                    return apiService.getUserInfo(loginResModel.getMemberId())
                            .map(new Function<ResultModel<UserInfo>, ResultModel<UserInfo>>() {
                                @Override
                                public ResultModel<UserInfo> apply(ResultModel<UserInfo> userInfoResultModel) throws Exception {
                                    if (userInfoResultModel.isSuccess() && userInfoResultModel.getData() != null) {
                                        //保存userToken
                                        userInfoResultModel.getData().setUserToken(loginResModel.getAccess_token());
                                    }
                                    return userInfoResultModel;
                                }
                            });
                }
                return Observable.error(new CustomThrowable(loginResModelResultModel.getMsg()));
            }
        });
    }
}